package priv.wjh.dependency.analyzer.asm;

import org.apache.maven.shared.dependency.analyzer.ClassFileVisitor;
import org.apache.maven.shared.dependency.analyzer.asm.DependencyClassFileVisitor;
import org.codehaus.plexus.util.DirectoryScanner;

import java.io.*;
import java.util.Set;

public class MyAnalyzer {
    static int count = 0;
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\W\\Desktop\\work\\wyc-confservice\\wyc-confServiceConsoleApi\\target\\classes\\com\\wanshun");
        acceptDirectory(file);
        System.out.println(count);
    }

    public static void visitClass(String path, InputStream in) {
        if (!path.endsWith(".class")) {
            throw new IllegalArgumentException("Path is not a class");
        }
        DependencyClassFileVisitor visitor = new DependencyClassFileVisitor();
        String className = path.substring(0, path.length() - 6);


        className = className.replace('/', '.');

        visitor.visitClass(className, in);
        Set<String> dependencies = visitor.getDependencies();
        boolean mark = false;
        for (String dependency : dependencies) {
            if (dependency.startsWith("com.wanshun.confservice")){
                mark = true;
                break;
            }
        }
        if (mark){
            System.out.println("============== " + className + " ==============");
            for (String dependency : dependencies) {
                if (dependency.startsWith("com.wanshun.confservice")){
                    System.out.println(dependency);
                }
            }
        }
        count++;
    }


    public static void acceptDirectory(File directory) throws IOException {
        DirectoryScanner scanner = new DirectoryScanner();

        scanner.setBasedir(directory);
        scanner.setIncludes(new String[]{"**/*.class"});

        scanner.scan();

        String[] paths = scanner.getIncludedFiles();

        for (String path : paths) {
            path = path.replace(File.separatorChar, '/');

            File file = new File(directory, path);

            try (InputStream in = new FileInputStream(file)) {
                visitClass(path, in);
            }

        }
    }
}
